package indi.youxiaozhong.http;


import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import fi.iki.elonen.NanoHTTPD;

import static fi.iki.elonen.NanoHTTPD.MIME_HTML;
import static fi.iki.elonen.NanoHTTPD.newFixedLengthResponse;

public class NanoHttpResponse {

    NanoHTTPD.IHTTPSession session;

    private String MIME_TYPE = MIME_HTML;

    private StringBuffer outdataString;

    private Map<String,String> header;

    private NanoHTTPD.Response.Status status;


    NanoHttpResponse(NanoHTTPD.IHTTPSession session){
        this.session =session;
    }


    public void setMime(String mime){
        this.MIME_TYPE = mime;
    }

    public void sendRedirect(String path){
        this.addHeader("location", path);
        this.setStatus(NanoHTTPD.Response.Status.FOUND);
    }

    public void setStatus(NanoHTTPD.Response.Status status){
        this.status = status;
    }

    public void write(Object data) throws IOException {
        if(outdataString==null){
            outdataString = new StringBuffer();
        }
        if(data == null) return;

        if(data instanceof NanoHttpRequest.RequestDispatcher){
           String html = ((NanoHttpRequest.RequestDispatcher)data).toHtml();
           this.MIME_TYPE = MIME_HTML;

           outdataString.append(html);
        }else{
            if(data instanceof JSONObject  || data instanceof JSONArray){
                this.MIME_TYPE = "text/json";
            }
            outdataString.append(data);
        }

    }

    public void addHeader(String name,String value){
        if(this.header == null){
            this.header = new HashMap<String, String>();
        }

        this.header.put(name,value);
    }

    public String getHeader(String name){
        return this.getHeader(name,null);
    }

    public String getHeader(String name,String defaultValue){
        String value=null;
        if(this.header != null){
            value = this.header.get(name);
        }
        if(value == null){
            return defaultValue;
        }else{
            return value;
        }
    }


    protected NanoHTTPD.Response Response(){
        NanoHTTPD.Response response;
        if(outdataString!=null) {
            response = newFixedLengthResponse(NanoHTTPD.Response.Status.OK, MIME_TYPE, outdataString.toString());
        }else{
            response = newFixedLengthResponse(NanoHTTPD.Response.Status.OK,MIME_TYPE,null);
        }

        if (this.header!=null){
            for (Map.Entry<String  , String> entry : this.header.entrySet()) {
                //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                response.addHeader(entry.getKey(),entry.getValue());
            }
        }

        if(this.status!=null) response.setStatus(this.status);
        return response;
    }
}
